﻿using Modbus.Device;
using Modbus.IO;
using System.IO.Ports;
using System.Net.Sockets;

namespace ModBusApp
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //COM3为串口名称，9600为波特率，Parity.None为校验位，8为数据位，StopBits.One为停止位
            var serialPort1 = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
            serialPort1.Open();

            IModbusSerialMaster master = ModbusSerialMaster.CreateRtu(serialPort1);
            byte slaveId = 1;//当前设备的地址为1
            var returnData = master.ReadHoldingRegisters(slaveId, 0, 2);
            serialPort1.Close();
            Console.WriteLine("湿度为：" + returnData[0] / (double)10);
            Console.WriteLine("温度为：" + returnData[1] / (double)10);
            Console.WriteLine();



            string ipAddress = "192.168.0.1"; // Modbus TCP 从机的 IP 地址
            int port = 502; // Modbus TCP 端口号

            // 创建 Modbus TCP 从机
            using (TcpClient tcpClient = new TcpClient(ipAddress, port))
            {
                ModbusIpMaster master1 = ModbusIpMaster.CreateIp(tcpClient);
                try
                {
                    ushort startAddress = 1000; // 寄存器起始地址
                    ushort numRegisters = 5; // 寄存器数量

                    // 读取保持寄存器数据
                    ushort[] registers = master1.ReadHoldingRegisters(slaveId, startAddress, numRegisters);

                    for (int i = 0; i < numRegisters; i++)
                    {
                        Console.WriteLine($"Register {startAddress + i} = {registers[i]}");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error: " + ex.Message);
                }
            }
        }
    }
}
